package com.ren.scale.excel_listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ren.scale.entity.ReclScaleClassify;
import com.ren.scale.entity.excel.ScaleClassify;
import com.ren.scale.service.ReclScaleClassifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashSet;


/**
 * @ClassName: ScaleClassifyExcelListener
 * @Description: TODO
 * @Author: RZY
 * @DATE: 2022/7/18 10:02
 * @Version: v1.0
 */

public class ScaleClassifyExcelListener extends AnalysisEventListener<ScaleClassify> {

    ReclScaleClassifyService scaleClassifyService;

    //已存在的一级分类标题数据集
    HashSet<String> firstClassifySet;

    //已存在的二级分类标题数据集
    HashSet<String> secondClassifySet;

    public ScaleClassifyExcelListener(ReclScaleClassifyService scaleClassifyService,
                                      HashSet<String> firstClassifySet,
                                      HashSet<String> secondClassifySet) {
        this.scaleClassifyService = scaleClassifyService;
        this.firstClassifySet = firstClassifySet;
        this.secondClassifySet = secondClassifySet;
    }


    // TODO 读取xls文件中的所有分类
    @Override
    public void invoke(ScaleClassify scaleClassify, AnalysisContext analysisContext) {
        System.out.println("scale:" + scaleClassify);
        //一级分类标题
        String firstClassifyTitle = scaleClassify.getFirstClassifyTitle();
        //二级分类标题
        String secondClassifyTitle = scaleClassify.getSecondClassifyTitle();
        //一级分类封装
        ReclScaleClassify firstClassify = null;
        //二级分类封装
        ReclScaleClassify secondClassify;
        try {
            //持久化一级分类
            if(!StringUtils.isEmpty(firstClassifyTitle) && !firstClassifySet.contains(firstClassifyTitle)) {
                firstClassify = new ReclScaleClassify();
                scaleClassifyService.save(firstClassify.setTitle(firstClassifyTitle).setParentId(0L));
            }
            //持久化二级分类
            if(!StringUtils.isEmpty(secondClassifyTitle) && !secondClassifySet.contains(secondClassifyTitle)) {
                secondClassify = new ReclScaleClassify();
                if (firstClassify != null) {
                    scaleClassifyService.save(secondClassify.setTitle(secondClassifyTitle).setParentId(firstClassify.getId()));
                }
            }
        } catch (Exception e) {
            System.out.printf("当前分类信息 {%s} 持久化失败, 失败原因 : {%s}", scaleClassify, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
